package edu.toronto.whimper.NoiseObjects;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class GPSReader {

	private LocationManager mlocManager;
	private Location currentLocation;
	private Context programContext;
	
	public GPSReader(Context inputProgramContext) {
		
		programContext = inputProgramContext;
		
		mlocManager = (LocationManager)programContext.getSystemService(Context.LOCATION_SERVICE);
		
		StartRecieving();

		currentLocation = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		
		if (currentLocation == null){
			currentLocation = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		}
		
	}
	
	protected void finalize() throws Throwable {
		StopRecieving();
	};

	public void StartRecieving(){
		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLcationChangeListener);
	}
	
	public void StopRecieving(){
		mlocManager.removeUpdates(myLcationChangeListener);
	}
	
	public Location GetCurrentLocation(){
		return currentLocation;
	}
	
	public double GetCurrentLocationLatitude(){
		if (currentLocation != null){
			return currentLocation.getLatitude();
		}else{
			return 0;
		}
	}
	
	public double GetCurrentLocationLongitude(){
		if (currentLocation != null){
			return currentLocation.getLongitude();
		}else{
			return 0;
		}
	}
	
	public double GetCurrentLocationAltitude(){
		if (currentLocation != null){
			return currentLocation.getAltitude();
		}else{
			return 0;
		}
	}
	
	LocationListener myLcationChangeListener=new LocationListener() {
		public void onLocationChanged(Location location) {
			currentLocation = location;
		}
		
		public void onProviderDisabled(String provider) {
			// required for interface, not used
		}
		
		public void onProviderEnabled(String provider) {
			// required for interface, not used
		}
		
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// required for interface, not used
		}
	};

}
